package activitis;

import java.text.SimpleDateFormat;
import java.util.Locale;

import servicios.ActualizacionPuntoService;
import utils.BaseAsync;
import utils.Constantes;
import utils.PreferencesHelper;

import com.example.rapichofer.R;
import com.google.gson.Gson;

import controladores.ControladorChoferes;
import controladores.ControladorTurnos;

import entidades.Movil;
import entidades.Turno;
import entidades.estados.Estados.EstadoChofer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class TurnoActivity extends BaseActivityCerrarSesion
{
	private Turno turno;
	
	private Button boton;
	private Switch switchDisponible;
	private TextView labelHoraInicio;
	private TextView labelMovil;
	private TextView labelPatente;
	
	private BroadcastReceiver receptor;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_turno);
		
		boton = (Button) findViewById(R.id.botonAccionTurno);
		labelHoraInicio = (TextView) findViewById(R.id.labelHoraInicio);
		labelMovil = (TextView) findViewById(R.id.labelMovil);
		labelPatente = (TextView) findViewById(R.id.labelPatente);
		switchDisponible = (Switch) findViewById(R.id.switchDisponible);
		
		receptor = new ReceptorSolicitud();
		
		new ActualizarTurno().execute();
		
		actualizar();
		
		Intent intent = new Intent(TurnoActivity.this,
				ActualizacionPuntoService.class);
		startService(intent);
	}
	
	public void switchClick (View view)
	{
		new CambiarEstado().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.turno, menu);
		return true;
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		
		IntentFilter filter = new IntentFilter(Constantes.FILTER_GCM.CHOFER);
		filter.setPriority(2);
		registerReceiver(receptor, filter);
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		
		unregisterReceiver(receptor);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == SeleccionMovilActivity.SELECCION_MOVIL)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String movilJson = data.getStringExtra(Constantes.DataBundle.MOVIL);
				
				if (movilJson != null)
				{
					Movil movil = new Gson().fromJson(movilJson, Movil.class);
					
					new IniciarTurno(movil.getId()).execute();
				}
			}
		}
	}
	
	private void actualizar ()
	{
		if (turno != null)
		{
			SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss", Locale.US);
			df.applyPattern("dd/MM/yyyy - HH:mm:ss");
			
			labelHoraInicio.setText(df.format(turno.getInicio().getTime()));
			
			//labelHoraInicio.setText(turno.getInicio().get(Calendar.YEAR) + "");
			
			Movil movil = turno.getMovil();
			
			if (movil != null)
			{
				labelMovil.setText(movil.getMarca() + " " + movil.getModelo());
				labelPatente.setText(movil.getPatente());
			}
			else
			{
				labelMovil.setText("No hay movil");
				labelPatente.setText("");
			}
			
			switchDisponible.setVisibility(View.VISIBLE);
			
			if (turno.getChofer().getEstado() == null)
			{
				switchDisponible.setChecked(true);
				new CambiarEstado().execute();
			}
			else
				switchDisponible.setChecked(turno.getChofer().getEstado().equals(EstadoChofer.DISPONIBLE));
			
			boton.setText("Finalizar");
		}
		else
		{
			labelHoraInicio.setText("Sin turno");
			labelMovil.setText("");
			labelPatente.setText("");
			
			switchDisponible.setVisibility(View.INVISIBLE);
			boton.setText("Iniciar");
		}
	}
	
	public void botonTurno (View view)
	{		
		if (turno != null)
			new CerrarTurno().execute();
		else
		{
			Intent intent = new Intent (TurnoActivity.this, SeleccionMovilActivity.class);
			startActivityForResult(intent, SeleccionMovilActivity.SELECCION_MOVIL);
		}
	}
	
	private class IniciarTurno extends BaseAsync
	{
		long idMovil;
		
		public IniciarTurno (long idMovil)
		{
			super(TurnoActivity.this, "Iniciando...");
			
			this.idMovil = idMovil;
		}
		
		@Override
		protected Void doInBackground(Void... params)
		{
			turno = new ControladorTurnos().iniciarTurno(new PreferencesHelper(getApplicationContext()).leerID(), idMovil);
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			if (turno == null)
				Toast.makeText(TurnoActivity.this, "Fallo.", Toast.LENGTH_SHORT).show();
			else
				actualizar();
		}
	}
	
	private class CerrarTurno extends BaseAsync
	{
		public CerrarTurno()
		{
			super(TurnoActivity.this, "Cerrando turno...");
		}
		
		@Override
		protected Void doInBackground (Void... params)
		{
			if (new ControladorTurnos().cerrarTurno(getIDChofer()))
				turno = null;
						
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			actualizar();
			super.onPostExecute(result);
		}
	}
	
	private class ActualizarTurno extends BaseAsync
	{
		public ActualizarTurno ()
		{
			super(TurnoActivity.this, "Espere <3");
		}
		
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}
		
		@Override
		protected Void doInBackground (Void... params)
		{
			turno = new ControladorTurnos().getTurno(getIDChofer());
						
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			actualizar();
			super.onPostExecute(result);
		}
	}
	
	private class CambiarEstado extends BaseAsync
	{
		public CambiarEstado()
		{
			super (TurnoActivity.this, "Cambiando estado...");
		}
		
		@Override
		protected Void doInBackground(Void... params)
		{
			boolean res;
			
			if (switchDisponible.isChecked())
				res = new ControladorChoferes().disponible(getIDChofer());
			else
				res = new ControladorChoferes().ocupado(getIDChofer());
			
			if (!res)
				switchDisponible.setChecked(!switchDisponible.isChecked());
			
			return null;
		}
	}
	
	private class ReceptorSolicitud extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			Log.i("LOG", "TurnoActivity, recibi GCM.");
			
			abortBroadcast();
			
			Bundle extras = intent.getExtras();
			
			switch (extras.getString("tipo"))
			{
			case Constantes.TipoGCM.SOLICITUD_VIAJE:
				sonar();
				Intent i = new Intent(TurnoActivity.this, RespuestaViajeActivity.class);
				i.putExtra("solicitud", extras.getString("object"));
				startActivity(i);
				break;
			case Constantes.TipoGCM.VIAJE_CANCELADO:
				sonar();
				AlertDialog alertDialog = new AlertDialog.Builder(TurnoActivity.this).create();
				alertDialog.setTitle("Viaje");
				alertDialog.setMessage("El viaje actual ha sido cancelado.");
				alertDialog.show();
				break;
			}
		}
		
		private void sonar ()
		{
			try 
			{
			    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
			    r.play();
			} 
			catch (Exception e) 
			{
			    e.printStackTrace();
			}
		}
	}
	
	private long getIDChofer ()
	{
		return new PreferencesHelper(getApplicationContext()).leerID();
	}
}
